/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.meego.common.queue;

import com.meego.common.log.GA;
import java.util.concurrent.ArrayBlockingQueue;

/**
 *
 * @author TueHM
 */
public class QueueImpl implements Queue {

    private ArrayBlockingQueue<QueueCommand> queue;
    private int workerNum;
    private int maxLength;
    private long msleepIdle;

    public QueueImpl(int workerNum, int maxLength) {
        this.workerNum = workerNum;
        this.maxLength = maxLength;
        this.msleepIdle = this.msleepIdle;
        this.queue = new ArrayBlockingQueue(maxLength);
    }

    public int size() {
        return this.queue.size();
    }

    public boolean put(QueueCommand i) {
        if (this.queue.remainingCapacity() < this.workerNum) {
            GA.service.error("Queue exceed max length!!!!!!");
            return false;
        }
        boolean ret = false;
        try {
            this.queue.put(i);
            ret = true;
        } catch (InterruptedException e) {
            GA.service.error("Exception in put", e);
        }
        return ret;
    }

    public QueueCommand take() {
        QueueCommand cmd = null;
        try {
            cmd = (QueueCommand) this.queue.take();
        } catch (InterruptedException e) {
            GA.service.error("Exception in take", e);
        }
        return cmd;
    }

    public void process() {
        for (int i = 0; i < this.workerNum; i++) {
            QueueWorker qw = new QueueWorker(this);
            new Thread(qw).start();
        }
    }

    public int getWorkerNum() {
        return this.workerNum;
    }

    public int getMaxLength() {
        return this.maxLength;
    }

    public int remaining() {
        return this.queue.remainingCapacity();
    }
}
